package com.yifei.service.auth;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.yifei.constants.RedisKeyConstants;
import com.yifei.utils.RedisUtil;
import com.yifei.utils.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;

import java.util.Set;

/**
 * @Description: Security 权限
 * @Author: yiFei
 * @date: 2023/9/25 14:57
 */
@Component("auth")
public class PermissionService {

    private static final Logger log = LoggerFactory.getLogger(PermissionService.class);
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 判断当前登录用户是否拥有操作权限
     *
     * @param perm 权限标识(eg: sys:user:add) (eg: sys:user:*)
     * @return 是否通过权限认证
     */
    public boolean hasPerm(String perm) {
        if (StrUtil.isBlank(perm)) {
            return false;
        }

        // 通过 用户ID 获取权限信息 ( 详情查看 JwtUtil )
        Long userId = SecurityUtil.getUserId();
        Set<String> perms = redisUtil.getCacheObject(RedisKeyConstants.USER_PERMS_CACHE_PREFIX + userId);

        // 用户无权限信息返回 false
        if (CollectionUtil.isEmpty(perms)) {
            return false;
        }

        // 通过 PatternMatchUtils 判断权限信息 （ *号匹配任意字符）
        boolean hasPermission = perms.stream()
                .anyMatch(item -> PatternMatchUtils.simpleMatch(perm, item));

        // 打印日志信息
        if (!hasPermission) {
            log.info("用户编号 :{} ,无权限标识: {}", userId, perm);
        }
        return hasPermission;
    }

}
